// JavaScript Document

/**
 * General Purpose Script To Upload and Save an Image To A DB
 * 
 * This script requires the presence of $p to provide the AJAX based data
 * transfer. Perhaps a simple library needs to used for consistency
**/

var picup = {
	
    container: null,
    fileField: null,
    imgPath: null,
    pictureField: null,
    thumbField: null,
    basePath: null,
    destFolder: null,
    thumbFolder: null,
    useSection: null,

    fields : {
		browse: null,
        uplink : null,
		clearLink: null,
        fileDiv: null
    },
	
    createDisplayArea: function() {
        var displayArea = document.createElement("div");
        displayArea.id = "displayArea";
        displayArea.style.width = "180px";
        displayArea.style.height = "160px";
        displayArea.style.border = "solid #ccc 1px";
        displayArea.style.backgroundColor = "#FFF";
        displayArea.style.marginLeft = "auto";
        displayArea.style.marginRight = "auto";
        displayArea.style.display = "table-cell";
        displayArea.style.verticalAlign = "middle";
        displayArea.style.overflow = "hidden";
        displayArea.style.textAlign = "center";
		
        if( picup.imgPath != null && picup.imgPath != "" && picup.imgPath != "none" ) {
            var initImg = document.createElement("img");
            initImg.src = picup.imgPath;
            initImg.width = 150;
            initImg.border = 0;
            initImg.align = "center";
            //initImg.style.border = "solid #999 1px";
            initImg.style.padding = "1px";
				
            displayArea.appendChild(initImg);
        }
		
		var browse = document.createElement("a");
		browse.id = "browse";
		browse.setAttribute("href","#");
		browse.innerHTML = "Browse";
		browse.onclick = function() {
			picup.browseForImage();
			return false;
		};
		
        // link to trigger upload
        var uplink = document.createElement("a");
        uplink.id = "uplink";
        uplink.setAttribute("href", "#");
        uplink.innerHTML = "Upload";
        uplink.onclick = function() {
            picup.showUploadField();
            return false;
        };
		
		// link to clear image
        var clearLink = document.createElement("a");
        clearLink.id = "clearLink";
        clearLink.setAttribute("href", "#");
		clearLink.innerHTML = "Clear";
        clearLink.onclick = function() {
            picup.clearImageData();
            return false;
        };
			
        picup.fields.uplink = uplink;
		picup.fields.clearLink = clearLink;
		picup.fields.browse = browse;
	
        // file input field to select image from system
        var fileField = document.createElement("input");
        fileField.type = "file";
		fileField.size = "12";
        fileField.id = "uploadFile";
        fileField.name = "uploadFile";
        fileField.style.marginLeft = "auto";
        fileField.style.marginRight = "auto";
        fileField.onchange = function() {
            if( picup.setDestinationFileName(this) ) {
                picup.doUpload();
            }
        }
			
        picup.fileField = fileField;
		
        // link to cancel upload action
        var closeLink = document.createElement("a");
        closeLink.setAttribute("href", "#");
        closeLink.id = "pu_close_link";
        closeLink.innerHTML = " Cancel";
        closeLink.onclick = function() {
            picup.fields.browse.style.display = "inline-block";
			picup.fields.uplink.style.display = "inline-block";
			picup.fields.clearLink.style.display = "inline-block";
            picup.fields.fileDiv.style.display = "none";
            return false;
        };
			
        // create upload form to hold input field and cancel link
        var inputDF = document.createElement("input"); // destFolder hidden field
        inputDF.type = "hidden";
        inputDF.name = "destFolder";
        inputDF.id = "destFolder";
        inputDF.value = picup.destFolder;

        var inputTF = document.createElement("input"); // thumbFolder hidden field
        inputTF.type = "hidden";
        inputTF.name = "thumbFolder";
        inputTF.id = "thumbFolder";
        inputTF.value = picup.thumbFolder;
		
        var inputPF = document.createElement("input"); // Upload Picture hidden field
        inputPF.type = "hidden";
        inputPF.name = "picup_Picture";
        inputPF.id = "picup_Picture";
		
        var submitBtn = document.createElement("input");
        submitBtn.type = "submit";
        submitBtn.name = "picup_submit";
        submitBtn.id = "picup_submit"
        submitBtn.value = "Upload";
        submitBtn.style.display = "none";
		
        var usHF = document.createElement("input");
        usHF.type = "hidden";
        usHF.name = "useSection";
        usHF.id = "useSection";
        usHF.value = picup.useSection != null ? picup.useSection : "cms";
		
		var siteHF = document.createElement("input");
		siteHF.type = "hidden";
		siteHF.name = "siteid";
		siteHF.id = "siteid";
		siteHF.value = picup.siteid;
			
        var form = document.createElement("form");
        //form.action = picup.basePath + "picup.php";
        form.action = "../cms/picup.php";
        form.target = "picup_frame";
        form.method = "post";
        form.enctype = "multipart/form-data";
        form.name = "picup_form";
        form.id = "picup_form";
        form.style.margin = "0px";
        form.appendChild( fileField );
        form.appendChild( inputDF);
        form.appendChild( inputTF);
        form.appendChild( inputPF);
		
		// only include the hidden field if an actual value is supplied
		if( picup.siteid > 0) {
			form.appendChild( siteHF );
		}
		
        form.appendChild( usHF );
        form.appendChild( document.createElement("br") );
        form.appendChild( closeLink );
        form.appendChild( submitBtn );
		
        // upload div
        var fileDiv = document.createElement("div");
        fileDiv.id = "fileDiv";
        fileDiv.style.textAlign = "center";
        fileDiv.style.display = "none";
        fileDiv.appendChild( form );
			
        picup.fields.fileDiv = fileDiv;
		
        // div to showing progress indicator
        var progImg = document.createElement("img");
        progImg.src = picup.basePath + "loadSnake.gif";
        progImg.border = 0;
        progImg.hspace = 5;
        progImg.align = "absmiddle";
		
		var progText = document.createElement("span");
			progText.id = "progress-text";
			progText.appendChild( document.createTextNode("Uploading...") );
		
        var progDiv = document.createElement("div");
        progDiv.id = "progDiv";
        progDiv.style.padding = "5px";
        progDiv.style.display = "none";
        progDiv.appendChild( progImg );
        progDiv.appendChild( progText );
			
		
        var linkDiv = document.createElement("div");
		linkDiv.id = "pu_links_div";
        linkDiv.style.padding = "5px";
        linkDiv.style.textAlign = "center";
		linkDiv.appendChild( browse );
        linkDiv.appendChild( uplink );
		linkDiv.appendChild( clearLink );
        linkDiv.appendChild(fileDiv);
        linkDiv.appendChild(progDiv);
		
		// use the addCSSRule function in the KAN $p global library
		addCSSRule("#pu_links_div a", "margin-left: 5px; margin-right: 5px;");
		
        var iframe = document.createElement("iframe");
        iframe.name = "picup_frame";
        iframe.id = "picup_frame";
        iframe.style.display = "none";
        iframe.height = 5;
        iframe.width = 5;
        iframe.onload = function() {
            picup.displayImage("picup_frame");
        };
		
        if( picup.container != null ) {
            picup.removeAll( picup.container );
            picup.container.style.marginLeft = "auto";
            picup.container.style.marginRight = "auto";
            picup.container.style.width = "200px";
            picup.container.style.overflow = "hidden";
            picup.container.appendChild(displayArea);
            picup.container.appendChild(linkDiv);
            picup.container.appendChild(iframe);
        }
    },
	
	appendBrowserToField: function() {
		if( !picup.pathField ) {
			return;
		}	
		
		var field = document.getElementById( picup.pathField );
		if( field == null ) {
			return;	
		}
		
		var browser = document.createElement("input");
		browser.type = "button";
		browser.value = "...";
		browser.name = "pu_browser";
		browser.onclick = function() {
			picup.browseForImage();
			return false;
		};
		
		field.parentNode.appendChild( browser );
	},
	
    showUploadField: function() {
		picup.fields.browse.style.display = "none";
        picup.fields.uplink.style.display = "none";
		picup.fields.clearLink.style.display = "none";
        picup.fields.fileDiv.style.display = "block";
    },
	
	clearImageData: function() {
		picup.removeAll( picup.getElement("displayArea") );
		
		if( picup.pictureField != null ) {
			picup.getElement( picup.pictureField ).value = "";
		}
		
		if( picup.thumbField != null ) {
			picup.getElement( picup.thumbField ).value = "";
		}
	},
	
    setDestinationFileName: function(field) {
        var url = document.getElementById("picup_Picture");
        var folder = document.getElementById("destFolder");
		
        if(url != null) {
            var now = new Date();
            var dateStr = now.getDate() + "" + now.getMonth() + "" + now.getFullYear() + "_" + now.getHours() + "" + now.getMinutes() + "" + now.getSeconds();
            var fileName = field.value;
            var ext = fileName.substring( fileName.lastIndexOf("."), fileName.length );
			
            if( ext.toLowerCase().indexOf("jpg") == -1 && ext.toLowerCase().indexOf("gif") == -1 &&
                ext.toLowerCase().indexOf("png") == -1 ) {
				
                alert("File To Be Uploaded Must Be In JPG, PNG or GIF Format");
                return false;
            }
			
            fileName = folder.value + "img" + dateStr + ext.toLowerCase();
			
            url.value = fileName;
			
            return true;
        }

        return false;
    },
	
    doUpload : function() {
        document.getElementById("picup_form").submit();
		
        picup.getElement("fileDiv").style.display = "none";
        picup.getElement("progDiv").style.display = "block";
    },
	
    displayImage: function(frameId) {
        if( window.navigator.userAgent.indexOf("MSIE") != -1 ) {
            if( document.getElementById(frameId).contentWindow.document.body.innerHTML != "") {
                document.getElementById("displayArea").innerHTML = document.getElementById(frameId).contentWindow.document.body.innerHTML;
            }
        } else {
            if( document.getElementById(frameId).contentDocument.body.innerHTML != "" ) {
                document.getElementById("displayArea").innerHTML = document.getElementById(frameId).contentDocument.body.innerHTML;
            }
        }
		
        picup.getElement("uplink").style.display = "inline-block";
		picup.getElement("browse").style.display = "inline-block";
		picup.getElement("clearLink").style.display = "inline-block";
        picup.getElement("progDiv").style.display = "none";
		
        if( document.getElementById("uploadedPic") != null ) {
            if( picup.pictureField != null ) {
                picup.getElement( picup.pictureField ).value = picup.getElement("picup_imgPath").value;
            }
			
            if( picup.thumbField != null ) {
                picup.getElement( picup.thumbField ).value = picup.getElement("picup_thumb").value;
            }
        }
    },
	
	showProgress: function(show, text) {
		if( !show ) {
			picup.getElement("uplink").style.display = "inline-block";
			picup.getElement("clearLink").style.display = "inline-block";
			picup.getElement("fileDiv").style.display = "none";
			picup.getElement("progDiv").style.display = "none";
			
			picup.getElement("progress-text").innerHTML = "Uploading...";
		} else {
			picup.getElement("uplink").style.display = "none";
			picup.getElement("clearLink").style.display = "none";
			picup.getElement("fileDiv").style.display = "none";
			picup.getElement("progDiv").style.display = "block";
			
			if( text ) {
				picup.getElement("progress-text").innerHTML = text;
			}
		}
	},
	
    showImage: function(imgPath, thumbPath) {

        $p("#displayArea *").remove();
		
		if( imgPath != null && imgPath != "" ) {
			var img = document.createElement("img");
			img.src = imgPath;
			img.border = 0;
			img.align = "center";
			//img.style.border = "solid #999 1px";
			img.style.padding = "1px";
			img.style.width = "150px";
			
			picup.getElement("displayArea").appendChild(img);
		}        
		
		if( picup.pictureField != null ) {
			picup.getElement( picup.pictureField ).value = imgPath;
		}
		
		if( picup.thumbField != null && thumbPath != null ) {
			picup.getElement( picup.thumbField ).value = thumbPath;
		}
    },
	
	browseForImage: function() {
		
		$p.showDialog({
			title: 'Images',
			content: 'Loading Images...',
			width: '800px',
			height: '500px'
		}, function() {
			$p.centerDialog();
			picup.loadImages(0,15);
		});
	},
	
	loadImages: function(start, limit) {
		var query = "action=load_images&start=" + start + "&limit=" + limit + "&use_section=" + picup.useSection;
		
		if( picup.siteid != -1 ) {
			query = query + "&siteid=" + picup.siteid;
		}
		
		$p.post('../cms/picup.php', query, function(data) {
            
            $p("#pm-pane-content").html(data);
			
			$p.all("#pm-pane-content .img-box img", function(el) {
				el.style.cursor = "pointer";
				$p.addEvent(el,'click',function(e) {
					picup.showImage( $p(this).attr('data-url'), $p(this).attr('data-thumb-url') );
					$p.hideDialog();
				});
			});
			
			$p("#pm-pane-content .img-box .delete-link").bind('click', function() {
				if( confirm('Delete This Image?') ) {
					var id = $p(this).attr("data-id");
					var query = "action=delete_images&id=" + id;
					
					$p.post("../cms/picup.php", query, function() {
						$p.remove('#img-box-' + id );
					});
				};	
			});
			
			$p.addEvent(".links-box a", 'click', function() {
				var page = this.getAttribute("data-page");
				picup.loadImages( (page - 1) * limit, limit );
			});
		});	
	},
	
    getElement: function(id) {
        return document.getElementById(id);
    },
	
    removeAll: function(obj) {
        var cn = obj.childNodes;
        if( cn != null ) {
            for(var i = 0; i < cn.length; i++) {
                obj.removeChild(cn[i]);
            }
        }
    },
	
    init: function(params) {
        var scripts = document.getElementsByTagName("script");
		
        for( var i = 0; i < scripts.length; i++) {
            if( scripts[i].src.indexOf("picup.js") != -1 ) {
                picup.basePath = scripts[i].src.substring(0, scripts[i].src.indexOf("picup.js") );
                break;
            }
        }
		
        if( params == null ) {
            return;
        }
		
        if( params.targetDiv != null ) {
            picup.container = document.getElementById( params.targetDiv );
        } else {
			// if the container does not exist, then this component cannot be created
			//return;	
		}
		
        params.imgPath != null ? picup.imgPath = params.imgPath : picup.imgPath = null;
        params.pictureField != null ? picup.pictureField = params.pictureField : picup.pictureField = null;
        params.thumbField != null ? picup.thumbField = params.thumbField : picup.thumbField = null;
        params.destFolder != null ? picup.destFolder = params.destFolder : picup.destFolder = "../assets/images/content/pics/";
        params.thumbFolder != null ? picup.thumbFolder = params.thumbFolder : picup.thumbFolder = "../assets/images/content/pics/";
        params.useSection != null ? picup.useSection = params.useSection : picup.useSection = "cms";
		params.siteid != null ? picup.siteid = params.siteid : picup.siteid = -1;
		
		picup.createDisplayArea();
		
		// add the CSS rules for the Browse Images Display
		addCSSRule(".nav-block", "overflow: hidden; padding: 10px; box-sizing: border-box;");
		addCSSRule(".nav-block .select-box", "float: left;");
		addCSSRule(".nav-block .links-box", "float: right;");
		
		addCSSRule(".img-box", "border: solid #ccc 1px; padding: 10px; float: left; margin-right: 5px; margin-left: 5px; margin-bottom: 10px; width: 120px; text-align: center; font-size: 11px;");
		addCSSRule(".img-box a", "margin-left: 5px; margin-right: 5px;");
		addCSSRule(".img-box img", "max-width: 90px; max-height: 90px;");
		
		addCSSRule(".links-box a", "margin-right: 2px; margin-right: 2px; padding: 2px 5px; background-color: #f5f5f5; border: solid #ccc 1px; color: #444;");
		addCSSRule(".links-box a:hover", "background-color: #444; color: #fff");
		addCSSRule(".links-box a.selected", "background-color: #222; color: #fff");
    }
};